package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.zhijian.medical.dao.local.RoutinePatientMapper;
import com.zhijian.medical.dao.local.RoutineSampleMapper;
import com.zhijian.medical.entity.po.RoutineHistory;
import com.zhijian.medical.entity.po.RoutinePatient;
import com.zhijian.medical.entity.po.RoutineSample;
import com.zhijian.medical.entity.po.RoutineStepRecord;
import com.zhijian.medical.entity.vo.request.RoutineHistorySearchVo;
import com.zhijian.medical.entity.vo.request.RoutineSampleSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.RoutineSampleSearchVo;
import com.zhijian.medical.entity.vo.response.RoutineSampleVo;
import com.zhijian.medical.enums.PatientEnums;
import com.zhijian.medical.enums.RoutineHistoryEnum;
import com.zhijian.medical.enums.RoutinePathologySampleStepEnum;
import com.zhijian.medical.service.RoutineHistoryService;
import com.zhijian.medical.service.RoutineSampleService;
import com.zhijian.medical.service.RoutineStepRecordService;
import com.zhijian.medical.service.RoutineStepService;
import com.zhijian.util.AssertUtil;
import com.zhijian.util.page.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 常规病例-样本业务处理层
 *
 * @author auto
 * @version: 1.0
 * @date 2024-06-26 15:47:43
 */
@Slf4j
@Service
public class RoutineSampleServiceImpl implements RoutineSampleService {

    @Autowired
    private RoutineSampleMapper mapper;

    @Autowired
    private RoutinePatientMapper routinePatientMapper;

    @Autowired
    private RoutineHistoryService historyService;

    @Autowired
    private RoutineStepService stepService;

    @Autowired
    private RoutineStepRecordService stepRecordService;


    @Override
    public RoutineSample selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public RoutineSampleVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteByIdList(List<Long> idList) {
        if (CollectionUtil.isEmpty(idList)) {
            return;
        }
        mapper.deleteByIdList(idList);
    }

    @Override
    public Long insert(RoutineSample routineSample) {
        Date now = new Date();
        routineSample.setCreateTime(now);
        routineSample.setUpdateTime(now);
        return mapper.insert(routineSample) > 0 ? routineSample.getId() : 0L;
    }

    @Override
    public Long insertSelective(RoutineSample routineSample) {
        Date now = new Date();
        routineSample.setCreateTime(now);
        routineSample.setUpdateTime(now);
        return mapper.insertSelective(routineSample) > 0 ? routineSample.getId() : 0L;
    }

    @Override
    public boolean update(RoutineSample routineSample) {
        Date now = new Date();
        routineSample.setUpdateTime(now);
        return mapper.updateByPrimaryKeySelective(routineSample) != 0;
    }

    @Override
    public boolean updateByPrimaryKeySelective(RoutineSample record) {
        Date now = new Date();
        record.setUpdateTime(now);
        return mapper.updateByPrimaryKeySelective(record) != 0;
    }

    @Override
    public boolean save(RoutineSampleSaveOrUpdateVo saveOrUpdateVo) {
        RoutineSample routineSample = new RoutineSample();
        BeanUtils.copyProperties(saveOrUpdateVo, routineSample);
        routineSample.setStep(RoutinePathologySampleStepEnum.GD.getCode().byteValue());
        return this.insertSelective(routineSample) != 0;
    }

    @Override
    public boolean deleteByPatientId(Long patientId) {
        return mapper.deleteByPatientId(patientId) != 0;
    }

    @Override
    public boolean modify(RoutineSampleSaveOrUpdateVo saveOrUpdateVo) {
        RoutineSample old = this.selectById(saveOrUpdateVo.getId());
        AssertUtil.notNull(old, "此数据不存在或者已被删除");
        RoutineSample routineSample = new RoutineSample();
        BeanUtils.copyProperties(saveOrUpdateVo, routineSample);
        return this.update(routineSample);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    public void batchUpd(List<RoutineSampleSaveOrUpdateVo.BatchUpdateFixedData> batchUpdateFixedDataList) {
        //固定
        Long routineSampleId = 0L;
        for (RoutineSampleSaveOrUpdateVo.BatchUpdateFixedData batchUpdateFixedData : batchUpdateFixedDataList){
            RoutineSample routineSample = new RoutineSample();
            routineSample.setId(batchUpdateFixedData.getId());
            routineSampleId = batchUpdateFixedData.getId();
            routineSample.setFixedWaterBatchNumber(batchUpdateFixedData.getFixedWaterBatchNumber());
            routineSample.setFixedWaterName("4%福尔马林");
            routineSample.setFixedTime(batchUpdateFixedData.getFixedTime());
            routineSample.setNote(batchUpdateFixedData.getNote());
            routineSample.setStep(RoutinePathologySampleStepEnum.GD.getCode().byteValue());
            mapper.updateByPrimaryKeySelective(routineSample);
        }
        //固定将会修改病人状态为注册正常
        if (routineSampleId > 0){
            RoutineSample sample = selectById(routineSampleId);
            RoutinePatient upd = new RoutinePatient();
            upd.setId(sample.getPatientId());
            upd.setState(PatientEnums.PatientStateEnum.GD_DONE.getCode());
            routinePatientMapper.updateByPrimaryKeySelective(upd);
            int count = historyService.count(RoutineHistorySearchVo.builder()
                    .conventionPathologyNumber(sample.getConventionPathologyNumber())
                    .step(RoutineHistoryEnum.GD.getCode().byteValue())
                    .number(sample.getConventionPathologyNumber())
                    .build());
            //只记录一次
            if (count <= 0){
                // 增加固定记录
                historyService.insert(RoutineHistory.builder()
                        .conventionPathologyNumber(sample.getConventionPathologyNumber())
                        .step(RoutineHistoryEnum.GD.getCode().byteValue())
                        .number(sample.getConventionPathologyNumber())
                        .build());
                // 增加病理号流程记录
                String contetnt = "在实验室固定";
                stepService.updateStepByNums(sample.getConventionPathologyNumber(), contetnt, RoutinePathologySampleStepEnum.GD.getCode().byteValue());
                stepRecordService.insert(RoutineStepRecord.builder()
                        .conventionPathologyNumber(sample.getConventionPathologyNumber())
                        .step(RoutinePathologySampleStepEnum.GD.getCode().byteValue())
                        .content(contetnt)
                        .build());
            }
        }
    }

    @Override
    public RoutineSampleVo selectOne(RoutineSampleSearchVo routineSampleSearchVo) {
        return mapper.selectOne(routineSampleSearchVo);
    }

    @Override
    public Integer count(RoutineSampleSearchVo routineSampleSearchVo) {
        return mapper.count(routineSampleSearchVo);
    }

    @Override
    public List<RoutineSampleVo> selectList(RoutineSampleSearchVo routineSampleSearchVo) {
        return mapper.selectList(routineSampleSearchVo);
    }

    @Override
    public Page<RoutineSampleVo> selectPage(RoutineSampleSearchVo routineSampleSearchVo) {
        AssertUtil.check(Objects.isNull(routineSampleSearchVo.getPageNum()) || Objects.isNull(routineSampleSearchVo.getPageSize()), "分页参数不能为空");
        //先直接查总数
        int count = count(routineSampleSearchVo);
        //分页
        Page<RoutineSampleVo> page = new Page<>(true, count, routineSampleSearchVo.getPageNum(), routineSampleSearchVo.getPageSize());
        routineSampleSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<RoutineSampleVo> responseVos = this.selectList(routineSampleSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public boolean insertBatch(List<RoutineSample> entities) {
        return CollectionUtil.isNotEmpty(entities) && mapper.insertBatch(entities) > 0;
    }

    @Override
    public void deleteByCondition(RoutineSampleSearchVo routineSampleSearchVo) {
        //慎重用此方法！！
        mapper.deleteByCondition(routineSampleSearchVo);
    }

}